<script setup lang="ts">
import { addPatient, delPatient, editPatient, getPatientList } from '@/services/user'
import type { Patient, PatientList } from '@/types/user'
import { computed, onMounted, ref } from 'vue'
import CpradioBtn from '@/components/cp-radioBtn.vue'
import { nameRules, idCardRules } from '@/utils/rules'
import { showConfirmDialog, showSuccessToast, showToast, type FormInstance } from 'vant'
import { useRoute } from 'vue-router'
import useConsultStore from '@/stores/modules/consult'
import router from '@/router'

// 患者信息
const patientList = ref<PatientList>([])
onMounted(async () => {
  // 等待数据加载完成
  await getPatient()

  // 当后台返回了数据，页面处于选中患者页面，则默认选中默认就诊人，否则就默认选中第一个
  if (isChange.value && patientList.value.length) {
    // 找到默认就诊人信息
    const defaultid = patientList.value.find((item) => item.defaultFlag === 1)
    if (defaultid) {
      // 将默认就诊人id绑定到选中id
      patientId.value = defaultid.id
    } else {
      // 将第一个就诊人id绑定给选中id
      patientId.value = patientList.value[0].id
    }
  }
})

// 封装获取患者信息方法
const getPatient = async () => {
  const res = await getPatientList()
  patientList.value = res.data
}

// 添加患者信息
const add = () => {
  // 显示右侧弹窗
  showClick()
}

//右侧弹窗
const showRight = ref(false) //默认不显示
// 显示弹窗方法
const showClick = () => {
  showRight.value = !showRight.value
  // 每次打开都将输入框的值重新赋值
  patient.value = { ...initPatient }
}

// 传入选择框配置信息
const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]

// 弹窗框的数据
const initPatient: Patient = {
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0
}

// 绑定输入框表单数据
const patient = ref<Patient>({
  ...initPatient
})

// 对默认就诊人进行数据转换
const defaultFlag = computed({
  get() {
    return patient.value.defaultFlag === 0 ? false : true
  },
  set(val) {
    patient.value.defaultFlag = val ? 1 : 0
  }
})

// 提交患者信息
const formRef = ref<FormInstance>()
const submit = async () => {
  // 校验表单的所有项
  await formRef.value?.validate()
  // 身份证倒数第二位，单数是男，双数是女
  const gender = +patient.value.idCard.slice(-2, -1) % 2
  if (gender !== patient.value.gender) {
    await showConfirmDialog({
      title: '温馨提示',
      message: '填写的性别和身份证号中的不一致\n您确认提交吗？'
    })
  }
  // 发起患者信息请求(根据有没有患者id来区分添加还是修改)
  patient.value.id ? await editPatient(patient.value) : await addPatient(patient.value)

  // 获取最新患者信息
  getPatient()

  // 关闭弹窗
  showRight.value = !showRight.value

  // 提示成功
  showSuccessToast(patient.value.id ? '编辑成功' : '添加成功')
}

// 编辑患者信息
const edit = (item: Patient) => {
  // 解构获取到的数据
  const { idCard, id, gender, defaultFlag, name } = item
  patient.value = { idCard, id, gender, defaultFlag, name }

  // 打开弹窗
  showRight.value = !showRight.value
}

// 删除患者信息
const remove = async () => {
  // 弹窗提示是否删除
  await showConfirmDialog({
    title: '温馨提示',
    message: `您确认要删除 ${patient.value.name} 患者信息吗 ？`
  })
  // 调用接口删除信息
  await delPatient(patient.value.id as string)
  // 关闭弹窗
  showRight.value = !showRight.value
  // 获取最新患者信息
  getPatient()
  // 提示删除成功
  showSuccessToast('删除成功')
}

// 选择患者
const route = useRoute()

const isChange = computed(() => {
  return route.query.isChange === '1'
})

// 选中患者
const patientId = ref<string>()
const select = (id: string | undefined) => {
  // 判断当前页面是否为选择患者信息页面
  if (isChange.value) {
    patientId.value = id
  }
}

// 记录患者id
const consultStore = useConsultStore()
const next = () => {
  if (!patientId.value) return showToast('请选就诊择患者')
  consultStore.setPatient(patientId.value)
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <CpNavbar :title="isChange ? '选择患者' : '家庭档案'"></CpNavbar>
    <!-- 头部提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list" v-if="patientList">
      <template v-for="item in patientList" :key="item.idCard">
        <div
          class="patient-item"
          @click="select(item.id)"
          :class="{ selected: patientId === item.id }"
        >
          <div class="info">
            <span class="name">{{ item.name }}</span>
            <span class="id">{{ item.idCard.replace(/^(.{6})(?:\d+)(.{4})$/, '\$1****\$2') }}</span>
            <span>{{ item.genderValue }}</span>
            <span>{{ item.age }}岁</span>
          </div>
          <div class="icon" @click="edit(item)">
            <CpIcons name="user-edit" />
          </div>
          <div class="tag" v-if="item.defaultFlag === 1 ? true : false">默认</div>
        </div>
      </template>
      <div class="patient-add" v-if="patientList.length < 6" @click="add">
        <CpIcons name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
    </div>
  </div>
  <!-- 右侧弹窗 -->
  <van-popup v-model:show="showRight" position="right" :style="{ width: '100%', height: '100%' }">
    <CpNavbar
      :title="patient.id ? '编辑患者' : '添加患者'"
      right-text="保存"
      :back="showClick"
      @click-right="submit"
    ></CpNavbar>

    <van-form autocomplete="off" ref="formRef">
      <van-field
        label="真实姓名"
        placeholder="请输入真实姓名"
        :rules="nameRules"
        v-model="patient.name"
      />
      <van-field
        label="身份证号"
        :rules="idCardRules"
        placeholder="请输入身份证号"
        v-model="patient.idCard"
      />
      <van-field label="性别" class="pb4">
        <template #input>
          <CpradioBtn :options="options" v-model="patient.gender" />
        </template>
      </van-field>
      <van-field label="默认就诊人">
        <template #input>
          <van-checkbox v-model="defaultFlag" :icon-size="18" round />
        </template>
      </van-field>
    </van-form>
    <van-action-bar v-if="patient.id">
      <van-action-bar-button @click="remove">删除</van-action-bar-button>
    </van-action-bar>
  </van-popup>
  <!-- 底部按钮 -->
  <div class="patient-next" v-if="isChange">
    <van-button type="primary" @click="next" round block>下一步</van-button>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;
  :global(.van-popup.van-popup--right) {
    padding-top: 46px !important;
  }
}
.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 30px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
.pb4 {
  padding-bottom: 4px;
}
// 底部操作栏
.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;
  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}
</style>
